package com.example.springboot.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.example.springboot.common.Result;
import com.example.springboot.entity.Banner;
import com.example.springboot.service.IBannerService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;

@RestController
@RequestMapping("/banners")
public class BannerController {
    @Autowired
    private IBannerService bannerService;

    /**
     * 获取所有激活的Banner
     *
     * @return 激活的Banner列表
     */
    @GetMapping
    public Result<List<Banner>> getActiveBanners() {
        List<Banner> banners = bannerService.list(new LambdaQueryWrapper<Banner>()
                .eq(Banner::getIsActivate, true)
                .orderByDesc(Banner::getCreatedAt));
        return Result.ok(banners);
    }

    /**
     * 获取所有Banner
     *
     * @return 所有Banner列表
     */
    @GetMapping("/all")
    public Result<List<Banner>> getAllBanners() {
        List<Banner> banners = bannerService.list(new LambdaQueryWrapper<Banner>()
                .orderByDesc(Banner::getCreatedAt));
        return Result.ok(banners);
    }

    /**
     * 分页获取Banner
     *
     * @param current 当前页
     * @param size 每页大小
     * @param active 是否只获取激活的Banner
     * @return 分页Banner数据
     */
    @GetMapping("/page")
    public Result<Page<Banner>> pageBanners(
            @RequestParam(defaultValue = "1") Integer current,
            @RequestParam(defaultValue = "10") Integer size,
            @RequestParam(required = false) Boolean active) {
        
        Page<Banner> page = new Page<>(current, size);
        LambdaQueryWrapper<Banner> queryWrapper = new LambdaQueryWrapper<>();
        
        // 如果指定了active参数，则按照激活状态筛选
        if (active != null) {
            queryWrapper.eq(Banner::getIsActivate, active);
        }
        
        queryWrapper.orderByDesc(Banner::getCreatedAt);
        
        Page<Banner> result = bannerService.page(page, queryWrapper);
        return Result.ok(result);
    }

    /**
     * 根据ID获取Banner
     *
     * @param id Banner ID
     * @return Banner详情
     */
    @GetMapping("/{id}")
    public Result<Banner> getBannerById(@PathVariable Long id) {
        Banner banner = bannerService.getById(id);
        if (banner == null) {
            return Result.error("Banner不存在");
        }
        return Result.ok(banner);
    }
}
